package com.aps.apspda.activity;

import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.adapter.PopDownAreaListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.StringCommonCallBack;
import com.aps.apspda.dialog.UserVerify2FragmentDialog;
import com.aps.apspda.dialog.UserVerifyFragmentDialog;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.EqpStatusEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.myview.ClearEditText;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class EqpStatusChangeActivity extends BaseActivity {


    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.tvMainStatus)
    TextView tvMainStatus;
    @BindView(R.id.tvSubStatus)
    TextView tvSubStatus;
    @BindView(R.id.tvEqpStatus)
    TextView tvEqpStatus;
    @BindView(R.id.tvStatus)
    TextView tvStatus;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.flArea)
    FrameLayout flArea;
    @BindView(R.id.etRemark)
    ClearEditText etRemark;

    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            EqpStatusChangeActivity.this.finish();
        }
    };

    private PopupWindow titlePop;
    private View popView;
    private Animation animation, animationDismiss;
    private RecyclerView lvDownList;
    private PopDownAreaListAdapter popDownAreaListAdapter;
    private EqpStatusEntity eqpStatusEntity;
    private EqpStatusEntity.StatusListBean.StatusBean selectBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_status_change;
    }

    @Override
    protected void initView() {
        popView = getLayoutInflater().inflate(R.layout.popupwindow_down_list_select, null);
        lvDownList = popView.findViewById(R.id.lvDownList);
        lvDownList.setLayoutManager(new LinearLayoutManager(EqpStatusChangeActivity.this));
        lvDownList.setItemAnimator(new DefaultItemAnimator());

        topView.setTitle("设备状态切换(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        topView.setTitleMode(TitleView.NORMAL_TEXT_MODE);
        topView.setRightListener("确定切换", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            EqpStatusChangeActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (selectBean == null) {
                    ToastUtils.showFreeToast("请选择要切换的设备状态",
                            EqpStatusChangeActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                // add by bunny  状态切换权限验证
                String fromStatus=tvSubStatus.getText().toString();//要切出状态
                String toStatus=tvStatus.getText().toString();//要切入状态
                if(fromStatus.equals("设备保养")||fromStatus.equals("工程用机")||toStatus.equals("设备保养")||toStatus.equals("工程用机"))
                {
                    final UserVerify2FragmentDialog userVerifyFragmentDialog2 = new UserVerify2FragmentDialog();
                    userVerifyFragmentDialog2.setCallBackAndWhere("权限验证", new StringCommonCallBack() {
                        @Override
                        public void onCallback(String str) {
                            userVerifyFragmentDialog2.dismiss();
                            if (str.contains("校验成功")) {
                                String USERID = str.substring(str.indexOf(",") + 1, str.indexOf(",",str.indexOf(",")+1));
                                String ENGUSERID = str.substring(str.indexOf(",",str.indexOf(",")+1)+1,str.length());
                                requestChange(USERID,ENGUSERID);
                            }
                        }
                    }, toStatus,fromStatus);
                    userVerifyFragmentDialog2.show(getSupportFragmentManager(), "USER_VERIFY_DIALOG");
                }
                else if(fromStatus.equals("非计划停机")||fromStatus.equals("计划停机")||toStatus.equals("非计划停机")||toStatus.equals("计划停机")) {
                    final UserVerifyFragmentDialog userVerifyFragmentDialog = new UserVerifyFragmentDialog();
                    userVerifyFragmentDialog.setCallBackAndWhere("权限验证", new StringCommonCallBack() {
                        @Override
                        public void onCallback(String str) {
                            userVerifyFragmentDialog.dismiss();
                            if (str.contains("校验成功")) {
                                String USERID = str.substring(str.indexOf(",") + 1, str.length());
                                requestChange(USERID,"");
                            }
                        }
                    }, toStatus,fromStatus);
                    userVerifyFragmentDialog.show(getSupportFragmentManager(), "USER_VERIFY_DIALOG");
                }
                else {  requestChange("","");}
                //end
            }
        });
    }

    private void requestChange(String USERID,String ENGUSERID) {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(EqpStatusChangeActivity.this)) {
                    mHandler.postDelayed(runnable, 1000);
                    loadSuccess(response.body().getMessage());
                } else {
                    loadFail(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ChangeEQPStatus");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        map.put("REMARK", etRemark.getText().toString().trim());
        map.put("MAINSTATUS", selectBean.getMAINSTATUS());
        map.put("FROMMAINSTATUS", eqpStatusEntity.getMAINSTATUS());
        map.put("SUBSTATUS", selectBean.getSUBSTATUS());
        map.put("FROMSUBSTATUS", eqpStatusEntity.getSUBSTATUS());
        map.put("TRANTYPE", selectBean.getTRAN_TYPE());
        map.put("CHECKOPID", USERID);
        map.put("ENGINEERCHECKOPID", ENGUSERID);
        NetUtils.requestNet(this, "/ChangeEQPStatus", map, callBack);
    }

    @Override
    protected void initData() {
        requestData();
    }

    private void requestData() {
        EntityCallBack<BaseEntity<EqpStatusEntity>> callBack = new DialogEntityCallBack<BaseEntity<EqpStatusEntity>>
                (new TypeToken<BaseEntity<EqpStatusEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<EqpStatusEntity>> response) {
                if (response.body().isSuccess(EqpStatusChangeActivity.this)) {
                    eqpStatusEntity = response.body().getData();
                    tvEqpId.setText(eqpStatusEntity.getEQPID());
                    tvMainStatus.setText(eqpStatusEntity.getMAINSTATUS());
                    tvSubStatus.setText(eqpStatusEntity.getSUBSTATUS());
                    tvEqpStatus.setText(eqpStatusEntity.getEQPSTATUS());
                } else {
                    loadFail(response.body().getMessage());
                    mHandler.postDelayed(runnable, 1000);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<EqpStatusEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowEQPStatus");
                mHandler.postDelayed(runnable, 1000);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/ShowEQPStatus", map, callBack);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
        OkGo.getInstance().cancelTag(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (titlePop == null) {
            titlePop = new PopupWindow(popView, flArea.getWidth(), RelativeLayout.LayoutParams.MATCH_PARENT, true);
            titlePop.setAnimationStyle(R.style.PopupWindowCenterAnimation);
            titlePop.setBackgroundDrawable(new BitmapDrawable());
            titlePop.setFocusable(true);
            titlePop.setOutsideTouchable(true);
            titlePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivArrow.startAnimation(animationDismiss);
                }
            });
        }
    }

    @OnClick({R.id.flArea})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    EqpStatusChangeActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            case R.id.flArea:
                showTypePop();
                break;
        }
    }

    private void showTypePop() {
        if (eqpStatusEntity.getStatusList().getStatus().size() == 0) {
            ToastUtils.showFreeToast("暂无状态数据", EqpStatusChangeActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }

        final List<String> list = new ArrayList<>();
        for (EqpStatusEntity.StatusListBean.StatusBean bean : eqpStatusEntity.getStatusList().getStatus()) {
            list.add(bean.getSUBSTATUS());
        }
        if (popDownAreaListAdapter == null) {
            popDownAreaListAdapter = new PopDownAreaListAdapter(list);
            popDownAreaListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
            popDownAreaListAdapter.isFirstOnly(false);
            popDownAreaListAdapter.setCurrentSelect(-1);
            lvDownList.setAdapter(popDownAreaListAdapter);
            popDownAreaListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    selectBean = eqpStatusEntity.getStatusList().getStatus().get(position);
                    popDownAreaListAdapter.setCurrentSelect(position);
                    popDownAreaListAdapter.notifyDataSetChanged();
                    tvStatus.setText(list.get(position));
                    titlePop.dismiss();
                }
            });
        }


        if (titlePop.isShowing()) {
            titlePop.dismiss();
        } else {
            if (animation == null) {
                animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(500);
                animation.setFillAfter(true);
            }
            ivArrow.startAnimation(animation);
            AppUtils.showAsDropDown(titlePop, flArea, 0, 0);
        }
    }
}
